<template>
  <div style="height: 100%;">
    <el-row :gutter="20">
      <el-col :span="19">
        <el-form :inline="true">
          <el-form-item label="搜索:">
            <el-input
              v-model="keywords"
              placeholder="请输入工号或者姓名"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchResource()">查找</el-button>
          </el-form-item>
          <el-form-item>
            <el-upload
              class="upload-demo"
              :action="BaseUrl+'/file/fileUpload'"
              :headers="headerObj"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="zipSuccess"
              :before-remove="beforeRemove"
              :limit="1"
              :on-exceed="handleExceed"
              :show-file-list="false"
              accept=".zip,.rar"
            >
              <el-button type="success">点击上传打分模板</el-button>
              <span slot="tip" class="el-upload__tip" style="margin-left: 2.5rem;font-size:15px;color: #55aa00;"
                    v-if="scorePath!=null && scorePath!=''">已上传</span>
              <span slot="tip" class="el-upload__tip" style="margin-left: 2.5rem;font-size:15px;color: #ce0003;" v-else>未上传</span>
              <div slot="tip" class="el-upload__tip">只能上传压缩文件</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-row :gutter="20" type="flex">
      <el-col :span="11">
        <div style="display: flex;align-items: center;">
          <h2 style="display: inline;">可选专家名单</h2>
          <el-select size="medium" v-model="lAbelId" filterable placeholder="请选择专家标签" style="margin-left: 20px;">
            <el-option
              v-for="item in options"
              :key="item.labelId"
              :label="item.labelName"
              :value="item.labelId">
            </el-option>
          </el-select>
        </div>

        <el-table
          :header-cell-style="{background:'#eef1f6',color:'#606266','text-align':'center'}"
          ref="staffTable"
          :key="tableKey"
          :data="showTable"
          :row-key="getRowKey"
          border
          fit
          highlight-current-row
          @selection-change="handleStaffChange"
        >
          <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
          <el-table-column label="工号" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.gh }}</span>
            </template>
          </el-table-column>

          <el-table-column label="部门" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.bm }}</span>
            </template>
          </el-table-column>

          <el-table-column label="姓名" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.xm }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="resource-page">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[5,10, 15]"
            :page-size="pagesize"
            :pager-count="7"
            layout=" prev, pager, next,sizes, jumper"
            :total="staffList.length"
          >
          </el-pagination>
        </div>
      </el-col>
      <el-col :span="2" style="text-align:center;">
        <div style="position: relative;top:50%;transform:translateY(-50%);">
          <div>
            <el-button
              @click="addStaff"
              type="primary"
              :disabled="!staffData.length"
              icon="el-icon-arrow-right"
              circle
            ></el-button>
          </div>

          <el-button
            @click="removeStaff"
            type="primary"
            :disabled="!selectedStaffData.length"
            icon="el-icon-arrow-left"
            circle
            style="margin-left: 0;margin-top: 10px;"
          ></el-button>
        </div>
      </el-col>
      <el-col :span="11">
        <div style="display: flex;align-items: center;">
          <h2 style="display: inline;">已选专家名单</h2>
          <el-select size="medium" v-model="batchClass" filterable placeholder="请选择分类" style="margin-left: 20px;">
            <el-option
              v-for="(item,index) in batchClassOptions"
              :key="index"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </div>
        <el-table
          ref="selectedStaffTable"
          :key="tableKey"
          :row-key="getRowKey"
          :data="showTableRight"
          border
          fit
          highlight-current-row
          :header-cell-style="{background:'#eef1f6',color:'#606266','text-align':'center'}"
          @selection-change="handleSelectedStaffChange"
        >
          <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
          <el-table-column label="工号" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.gh }}</span>
            </template>
          </el-table-column>

          <el-table-column label="部门" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.depName!=''">{{ scope.row.depName }}</span>
              <span v-else>未填写</span>
            </template>
          </el-table-column>

          <el-table-column label="姓名" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="resource-page">
          <el-pagination
            @size-change="handleSizeRightChange"
            @current-change="handleCurrentRightChange"
            :page-sizes="[5,10, 15]"
            :page-size="rightPagesize"
            :pager-count="7"
            layout=" prev, pager, next,sizes, jumper"
            :total="selectedStaffList.length"
          >
          </el-pagination>
        </div>
      </el-col>
    </el-row>

  </div>


</template>
<script>
  export default {
    created() {
      console.log(this.BaseUrl)
      this.getAllteacher()
      this.getAllLabels()
      this.getAllExpertAxios()
      this.getBatchInfo()
      this.getAllExpertByBatchId()
    },
    mounted() {
    },
    data() {
      return {
        BaseUrl: process.env.Base_API,
        //上传方法调用请求头部
        headerObj: {
          token: this.$store.state.token,
          tokenHead: this.$store.state.tokenHead,
          jsession_id: this.$store.state.jsession_id
        },
        batchInfo: {},
        //批次Id
        batchId: this.$route.query.batchId,
        filterDataShow: [], //储存符合条件的数据-
        //搜索关键字
        keywords: "",
        //分页数据
        pagesize: 10,
        currentPage: 1,
        rightPagesize: 10,
        rightCurrentPage: 1,
        listLoading: true,
        //左侧表格数据
        staffList: [],
        //右侧表格数据
        selectedStaffList: [],
        //左侧预选数据
        staffData: [],
        //右侧预选数据
        selectedStaffData: [],
        tableKey: 0,
        rowKey: "rowKey",
        //存储标签选择
        options: [],
        //存储批次标签
        batchClassOptions: [],
        batchClass: '',
        batchExpert: '',
        //标签ID
        lAbelId: '',
        //存储全部专家信息
        allExpert: [],
        //存储全部教师信息
        allTeacherInfo: [],
        //打分模板地址
        scorePath: '',
        scorePathName: ''
      }
    },
    computed: {
      //showTable计算属性通过slice方法计算表格当前应显示的数据（左侧数据）
      showTable() {
        return this.filterDataShow.slice(
          (this.currentPage - 1) * this.pagesize,
          this.currentPage * this.pagesize
        );
      },
      //showTable计算属性通过slice方法计算表格当前应显示的数据（右侧数据）
      showTableRight() {
        return this.selectedStaffList.slice(
          (this.rightCurrentPage - 1) * this.rightPagesize,
          this.rightCurrentPage * this.rightPagesize
        );
      },
    },
    watch: {
      //监听搜索框内容，当搜索框内容发生变化时调用searchResource方法
      keywords() {
        if (this.keywords == '') {
          this.searchResource();
        }
      },
      lAbelId() {
        this.showLeftByLabelId()
      },
      batchClass() {
        this.showRightByClass()
      }
    },
    methods: {
      zipSuccess(response) {
        console.log(response)
        this.scorePath = response.data[0].filePath
        this.scorePathName = response.data[0].fileName
        this.updateScorePath()
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      //得到该批次信息
      getBatchInfo() {
        var tempFileName = {}
        this.$api.batch.getAllBatchById({batchId: this.batchId}).then((response) => {
          console.log(response)
          this.batchInfo = response.data.data[0]
          console.log(this.batchInfo)
          this.batchClassOptions = this.batchInfo.classifyName.split(",")
          this.scorePath = this.batchInfo.scorePath
        })
      },
      //更新评分路径
      updateScorePath() {
        this.$api.phase.updateScore({
          batchId: this.batchId,
          scorePath: this.scorePath,
          scorePathName: this.scorePathName,
        }).then((res) => {
          console.log(res)
        })
      },
      showRightByClass() {
        //数组清空
        this.$refs["selectedStaffTable"].clearSelection();
        this.selectedStaffList = []
        this.selectedStaffList = this.batchExpert.filter(item => item.classification == this.batchClass)
        this.searchResource()
      },
      showLeftByLabelId() {
        //数组清空
        this.staffList = []
        //定义专家的工号数组
        var ghs = []
        //获得专家的工号
        for (let i = 0; i < this.allExpert.length; i++) {
          if (this.lAbelId == this.allExpert[i].labelId) {
            ghs.push(this.allExpert[i].gh)
          }
        }
        //根据专家工号获取专家教师信息
        for (let i = 0; i < ghs.length; i++) {
          for (let j = 0; j < this.allTeacherInfo.length; j++) {
            if (ghs[i] == this.allTeacherInfo[j].gh) {
              this.staffList.push(this.allTeacherInfo[j])
            }
          }
        }
        //显示页面
        this.searchResource()
      },
      //绑定专家和批次关系
      addExpertToBatch() {
        //存储已选中的专家信息
        var expertsInfo = []
        //进行格式调整
        var expert = {gh: '', depName: '', name: ''}
        for (let i = 0; i < this.staffData.length; i++) {
          expert.gh = this.staffData[i].gh
          expert.depName = this.staffData[i].bm
          expert.name = this.staffData[i].xm
          this.$set(expert, 'batchId', this.batchId)
          this.$set(expert, 'classification', this.batchClass)
          this.$set(expert, 'type', 1)
          expertsInfo.push(JSON.parse(JSON.stringify(expert)))
        }
        //调用api，格式为"expertId": 2,"gh": "090008","depName": "医学院","batchId": "0498E6C1930F4066A60172933DA8E2B9","name": "张三","classification": "文科", "ptId": null
        this.$api.expert.creatExpert({experts: JSON.stringify(expertsInfo)}).then((response) => {
          console.log(response)
          if (response.data.code == 200) {
            this.$message({
              showClose: true,
              message: "专家添加成功！",
              type: "success",
              center: true,
              offset: (screen.height / 2) - 200,
              duration: 1000
            })
          } else {
            this.$message({
              showClose: true,
              message: "专家添加失败！",
              type: "error",
              center: true,
              offset: (screen.height / 2) - 200,
              duration: 1000
            })
          }
          this.getAllExpertByBatchId()
        })
      },
      deleteExpertAxios() {
        var TempExperts = []
        for (let i = 0; i < this.batchExpert.length; i++) {
          for (let j = 0; j < this.selectedStaffData.length; j++) {
            if (this.selectedStaffData[j].gh == this.batchExpert[i].gh && this.batchExpert[i].classification == this.batchClass) {
              TempExperts.push(this.batchExpert[i])
            }
          }
        }
        this.$api.expert.deleteExpert({experts: JSON.stringify(TempExperts)}).then((response) => {
          console.log(response)
          if (response.data.code == 200) {
            this.$message({
              showClose: true,
              message: "专家移除成功！",
              type: "success",
              center: true,
              offset: (screen.height / 2) - 200,
              duration: 1000
            })
          } else {
            this.$message({
              showClose: true,
              message: "专家移除失败！",
              type: "error",
              center: true,
              offset: (screen.height / 2) - 200,
              duration: 1000
            })
          }
          this.getAllExpertByBatchId()
        })
      },
      searchResource() {
        var numReg = /^[0-9]*$/
        var numRe = new RegExp(numReg)
        this.currentPage = 1; //将当前页设置为1，确保每次都是从第一页开始搜
        let filterKeywords = this.keywords.trim();
        let filerReasource = this.staffList.filter((item) => {
          //过滤全部数据
          if (!numRe.test(filterKeywords)) {
            if (item.xm.includes(filterKeywords)) {
              return item;
            }
          } else {
            if (item.gh.includes(filterKeywords)) {
              return item;
            }
          }
        });
        this.filterDataShow = filerReasource; //将符合条件的内容赋给filterDataShow
      },
      getRowKey(row) {
        //得到当前行的key值用于保留分页前的数据
        return row.gh
      },
      handleSizeChange(psize) {
        this.pagesize = psize;
      },
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage;
      },
      handleSizeRightChange(psize) {
        this.rightPagesize = psize;
      },
      handleCurrentRightChange(currentPage) {
        this.rightCurrentPage = currentPage;
      },
      getAllteacher() {
        this.$api.teacher.getAllTeacherInfo().then((response) => {
          console.log(response)
          this.allTeacherInfo = response.data.data
          this.searchResource()
        })
      },
      // 将左边表格选择项存入staffData中
      handleStaffChange(rows) {
        this.staffData = [];
        if (rows) {
          rows.forEach(row => {
            if (row) {
              this.staffData.push(row);
            }
          });
        }
      },
      // 左边表格选择项移到右边
      addStaff() {
        var gs = {gh: '', name: '', depName: ''}
        if (this.batchClass === '') {
          this.$message({
            showClose: true,
            message: "请选择要添加的批次分类！",
            type: "warning",
            center: true,
            offset: (screen.height / 2) - 200,
            duration: 2000
          })
          return
        }
        for (let j = 0; j < this.selectedStaffList.length; j++) {
          for (let i = 0; i < this.staffData.length; i++) {
            if (this.staffData[i].gh == this.selectedStaffList[j].gh) {
              this.$message({
                showClose: true,
                message: "该专家已添加到该分类中！",
                type: "warning",
                center: true,
                offset: (screen.height / 2) - 200,
                duration: 1000
              })
              return
            }
          }
        }
        setTimeout(() => {
          this.$refs["staffTable"].clearSelection();
          this.$refs["selectedStaffTable"].clearSelection();
        }, 0);
        //左侧值push到右侧表格
        this.staffData.forEach(item => {
          gs.gh = item.gh
          gs.name = item.xm
          gs.depName = item.bm
          this.selectedStaffList.push(JSON.parse(JSON.stringify(gs)));
        });
        this.addExpertToBatch()
      },
      // 右边表格选择项移到左边
      removeStaff() {
        setTimeout(() => {
          this.$refs["staffTable"].clearSelection();
          this.$refs["selectedStaffTable"].clearSelection();
        }, 0);
        for (let i = 0; i < this.selectedStaffList.length; i++) {
          for (let j = 0; j < this.selectedStaffData.length; j++) {
            if (
              this.selectedStaffList[i] &&
              this.selectedStaffData[j] &&
              this.selectedStaffList[i].gh === this.selectedStaffData[j].gh
            ) {
              this.selectedStaffList.splice(i, 1);

              this.searchResource()
            }
          }
        }
        this.deleteExpertAxios()
      },
      // 将右边表格选择项存入selectedStaffData中
      handleSelectedStaffChange(rows) {
        console.log(rows)
        this.selectedStaffData = [];
        if (rows) {
          rows.forEach(row => {
            if (row) {
              this.selectedStaffData.push(row);
            }
          });
        }
      },
      getAllExpertByBatchId() {
        this.$api.expert.getExpertByBatchId({batchId: this.batchId}).then((response) => {
          console.log("getAllExpertByBatchId:")
          console.log(response)
          this.batchExpert = response.data.data
        })
      },
      getAllLabels() {
        this.$api.Label.getLabels().then((response) => {
          this.options = response.data.data
        })
      },
      getAllExpertAxios() {
        this.$api.Label.getExpertLabels().then((response) => {
          this.allExpert = response.data.data
        })
      }

    }
  }
</script>
